import sys
from configobj import ConfigObj
from optparse import OptionParser
from swift.common.utils import parse_options

"""
read/update specified key against config file

command 'python config.py CONF -a modify -s sec1 -k key1 -x value1' =>
modify key1 in sec1 to value1 in CONF file if key exist, add the key if not exist.
"""

if __name__ == "__main__":
    parser = OptionParser("%prog CONFIG [options]")
    parser.add_option('-a', '--action',
                      help='specify action [read/modify]', default='read')
    parser.add_option('-s', '--section',
                      help='config section')
    parser.add_option('-k', '--key',
                      help='config key')
    parser.add_option('-x', '--value',
                      help='value to update')

    conf_file, options = parse_options(parser=parser)

    action = options.get('action', 'read')
    section = options.get('section')
    key = options.get('key')
    value = options.get('value')

    config = ConfigObj(conf_file)
    section_obj = None
    key_obj = None
    if section:
        section_obj = config.get(section, None)
    if section_obj and key:
        key_obj = section_obj.get(key, None)

    if action == 'read':
        if not section_obj:
            target = config
        elif not key_obj:
            target = section_obj
        else:
            target = key_obj
        if target == None:
            print "read target not found in config file %s" % conf_file
            sys.exit(1)
        print target
    elif action == 'modify':
        if not section or not key or not value:
            print "section, key, value must be specified to modify a key"
            sys.exit(1)
        if not section_obj:
            config[section] = {}
        config[section][key] = value
        config.write()
        print "successfully updated key [%s] with value [%s] in config file [%s]" % (key, value, conf_file)
    else:
        print "unsupported action %s" % action
        sys.exit(1)





